package com.lap.i18n.starter.interceptor;

import com.lap.i18n.starter.LangEnum;
import com.lap.i18n.starter.entity.LocalInfo;
import com.lap.i18n.starter.helper.LangHelper;
import com.lap.i18n.starter.tools.Constant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 语言拦截器
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
public class I18nInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) {
    String newLocale =
        StringUtils.defaultIfBlank(
            request.getParameter(Constant.LANG), request.getHeader(Constant.LANG));
    LangEnum lang = LangEnum.getStoreCode(newLocale);
    LangHelper.set(new LocalInfo(lang.getLang(), lang.getStoreLang()));
    return true;
  }

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    LangHelper.remove();
  }
}
